package me.zhengjie.modules.fileupload.domain;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 统一返回结果封装类
 *
 * @param <T> 泛型类型
 */
@Data
@Accessors(chain = true)
@ApiModel(value = "Result", description = "统一返回结果")
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private static final int SUCCESS_CODE = 200;
    private static final int FAIL_CODE = 500;

    @ApiModelProperty(value = "状态码", example = "200")
    private Integer code;

    @ApiModelProperty(value = "返回消息", example = "操作成功")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private T data;

    @ApiModelProperty(value = "时间戳", example = "1672531200000")
    private Long timestamp;

    @ApiModelProperty(value = "附加数据")
    private Map<String, Object> extra;

    public Result() {
        this.timestamp = System.currentTimeMillis();
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>()
                .setCode(SUCCESS_CODE)
                .setMessage("success")
                .setData(data);
    }

    public static <T> Result<T> fail(String message) {
        return fail(FAIL_CODE, message);
    }

    public static <T> Result<T> fail(int code, String message) {
        return new Result<T>()
                .setCode(code)
                .setMessage(message);
    }

    public Result<T> addExtra(String key, Object value) {
        if (this.extra == null) {
            this.extra = new HashMap<>();
        }
        this.extra.put(key, value);
        return this;
    }
}
